package com.siyoumi.app.modules.iot.admin;

import com.siyoumi.app.entity.IotDevice;
import com.siyoumi.app.entity.IotProduct;
import com.siyoumi.app.modules.iot.entity.IotPinCode;
import com.siyoumi.app.modules.iot.service.DeviceActionHandle;
import com.siyoumi.app.modules.iot.service.SvcIotDevice;
import com.siyoumi.app.modules.iot.service.SvcIotProduct;
import com.siyoumi.app.modules.iot.vo.VaIotDevice;
import com.siyoumi.component.XRedis;
import com.siyoumi.component.http.InputData;
import com.siyoumi.controller.AdminApiController;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XJson;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.experimental.Helper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/xadmin/iot/iot__device__edit")
public class iot__device__edit
        extends AdminApiController {
    @GetMapping()
    public XReturn index() {
        setPageTitle("设备-编辑");

        InputData inputData = InputData.fromRequest();

        boolean deviceState = false; //是否开机
        Map<String, Object> data = new HashMap<>();
        data.put("idev_order", 0);
        if (isAdminEdit()) {
            IotDevice entity = SvcIotDevice.getApp().loadEntity(getID());

            HashMap<String, Object> dataAppend = new LinkedHashMap<>();
            dataAppend.put("id", entity.getKey());
            //
            //合并
            data = entity.toMap();
            data.putAll(dataAppend);

            deviceState = getDeviceState(entity);
        }
        getR().setData("data", data);
        setPageInfo("device_state", deviceState);

        //产品
        JoinWrapperPlus<IotProduct> query = SvcIotProduct.getBean().listQuery();
        query.select("ipro_id", "ipro_name");
        List<Map<String, Object>> listProduct = SvcIotProduct.getApp().getMaps(query);
        setPageInfo("list_product", listProduct);

        return getR();
    }

    public boolean getDeviceState(IotDevice entity) {
        String actionId = SvcIotDevice.getBean().getMqttQueueId(entity);
        String val = XRedis.getBean().get(DeviceActionHandle.callbackKey(actionId));
        if (XStr.isNullOrEmpty(val)) {
            return false;
        }
        XReturn r = XJson.parseObject(val, XReturn.class);
        return r.getData("client_state", false);
    }

    @Transactional
    @PostMapping("/save")
    public XReturn save(@Validated() VaIotDevice vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result);
        //
        JoinWrapperPlus<IotDevice> query = SvcIotDevice.getBean().listQuery();
        query.eq("idev_num", vo.getIdev_num());
        if (isAdminEdit()) {
            query.ne("idev_id", getID());
        }
        IotDevice entityDev = SvcIotDevice.getApp().first(query);
        if (entityDev != null) {
            result.addError(XValidator.getErr("idev_num", "设备号已存在"));
        }
        XValidator.getResult(result);

        if (!isAdminEdit()) {
            vo.setIdev_acc_id(getAccId());
        }

        InputData inputData = InputData.fromRequest();
        return SvcIotDevice.getBean().edit(inputData, vo);
    }


    /**
     * 发送指令
     */
    @GetMapping("action")
    public XReturn action() {
        if (XStr.isNullOrEmpty(getID())) {
            return EnumSys.MISS_VAL.getR("miss id");
        }
        IotDevice entityDevice = SvcIotDevice.getApp().first(getID());
        XReturn r = SvcIotDevice.getBean().checkDevice(entityDevice);
        if (r.err()) {
            return r;
        }

        IotProduct entityPro = SvcIotProduct.getApp().first(entityDevice.getIdev_pro_id());

        DeviceActionHandle handle = DeviceActionHandle.getInstance(entityPro);
        return handle.send(entityDevice);
    }

    /**
     * 发送指令
     */
    @GetMapping("device_callback")
    public XReturn deviceCallback() {
        String actionId = input("action_id");
        if (XStr.isNullOrEmpty(getID())) {
            return EnumSys.MISS_VAL.getR("miss id");
        }
        if (XStr.isNullOrEmpty(actionId)) {
            return EnumSys.MISS_VAL.getR("miss action_id");
        }

        IotDevice entityDevice = SvcIotDevice.getApp().first(getID());
        XReturn r = SvcIotDevice.getBean().checkDevice(entityDevice);
        if (r.err()) {
            return r;
        }

        IotProduct entityPro = SvcIotProduct.getApp().first(entityDevice.getIdev_pro_id());

        DeviceActionHandle handle = DeviceActionHandle.getInstance(entityPro);
        return handle.callback(actionId);
    }
}
